package com.wyx.Filter;

import com.alibaba.fastjson.JSON;
import com.wyx.Common.Result;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.dsig.spec.XPathType;
import java.io.IOException;
/**
 * 登录验证拦截器
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LogincheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        /**
         * 设置不需要拦截的url
         */
        String[] urls = {
                "/pages/**",
                "/users/**",
                "/css/**",
                "/elementui/**",
                "/images/**",
                "/js/**",
                "/plugins/**",
        };
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        if (check(requestURI,urls)){
            //是上面那些不需要拦截的就直接放行
            filterChain.doFilter(request,response);
        }else {
            //否则的话
            String user = (String) request.getSession().getAttribute("user");
            System.out.println(user);
            if (user==null){
                Result<String>result=new Result<>(null,777,"NOTLOGIN");
                response.getWriter().write(JSON.toJSONString(result));
                return;
            }
            filterChain.doFilter(request,response);
        }
    }

    public Boolean check(String requrl,String[]urls){
        for (String url : urls) {
            if (PATH_MATCHER.match(url,requrl)){
                return true;
            }
        }
        return false;
    }
}
